<template>
    <el-upload class="file-uploader" 
		v-bind="$attrs"
		:multiple="multiple"
		:on-change="handleUploadChange"
        :before-upload="handleBeforeUpload" 
		:before-remove="handleBeforeRemove"
		:on-success = "handleSuccess"
		:auto-upload="true"  
		:file-list="showFiles">
        <slot></slot>
        <div slot="tip" class="el-upload__tip">{{this.tip}}</div>
    </el-upload>
</template>
<script>
export default {
    props: {
        accept: Array,
        limit: Number,
        fileList: Array,
		listType: String,
        multiple: Boolean,
		//最大上传尺寸
		maxSize: {
			type: Number,
			default: 20
		}
    },
    data() {
        return {
            fileAccept: this.accept,
            extStr: "",
            selectFiles: [],
            tip: "",
            showFiles: this.fileList ? [...this.fileList] : [],
            uploadFiles: this.fileList ? [...this.fileList] : [],
			isBefore: false	//判断当前是上传前，还是上传后
        }
    },
    computed: {
        acceptExt() {
            return this.fileAccept.map((item)=>{
				return `.${item}`
			}).join(",")
        }
    },
    methods: {
        handleUploadChange(file, fileList) {
			this.isBefore = true
        },
        handleBeforeRemove(file, fileList) {
			return this.$confirm(`确定移除 ${file.name}？`).then(() => {
				let index = this.uploadFiles.findIndex(item => item.uid === file.uid)
				this.uploadFiles.splice(index, 1)
				//这里没有进行物理删除，明天确认一下是否需要进行真实物理删除
				this.$message.success("删除成功")
				this.$emit('on-complete', this.uploadFiles)
			})
        },
        handleBeforeUpload(file) {
			this.isBefore = true
            const fileSuffix = file.name.substring(file.name.lastIndexOf(".")+1)
			console.log(fileSuffix,this.fileAccept)
            if (this.fileAccept.indexOf(fileSuffix) === -1) {
                this.$message.error(`上传文件只能是 ${this.extStr} 格式`)
                return false
            }

            const overMax = file.size / 1024 / 1024 < this.maxSize

            if (!overMax) {
                this.$message.error(`上传文件大小不能超过 ${this.maxSize}MB`)
                return false
            }

        },
		handleSuccess(response, file, fileList){
			let obj = {
				fileName: response.data.fileName,
				uid: file.uid,
				status: file.status,
				ossId: response.data.ossId,
				url: response.data.url
			}
			this.uploadFiles.push(obj)
			console.log("上传完成=====>",this.uploadFiles)
			this.$emit('on-complete', this.uploadFiles)
			this.isBefore = false
		},
    },
    watch: {

    },
    cteated() {

    },
    mounted() {
        this.extStr = this.fileAccept.join("、")
        this.tip = `仅支持 ${this.extStr} 格式,大小不能超过 ${this.maxSize}MB，最大上传 ${this.limit} 个文件`
    }
}
</script>
<style lang="scss" scoped>
::v-deep .el-upload-list{
	display: inline-block;
	.el-icon-close{
		top:6px;
	}
}
</style>
